<?php
/*
*	@数据库类
*	@Author Zero
*	@Email loveyangmao@126.com
*
*/
if(!defined('IN_SITE')) exit('Access Denied');


class db {

	#公有属性
    var  $link;
	var  $data;
	var  $fields;
	var  $row;
	var  $row_num;
	var  $insertid;
	var  $version;
	var  $affected_rows;
	var  $query_num = 0;
	var  $debug;
	var  $table;
	var  $lang;//语言包
	var  $user;
	var  $pass;
	var  $host;
	var  $db;
	var  $pdo;

	var $sql;


	function __construct($dsn) {
		if($GLOBALS['_CONFIG']['db']['debug']) {
			$this->pdo = new PDO($dsn);
		}
		else {
			try {  
				$this->pdo = new PDO($dsn);
			}
			catch (PDOException $e) {
				exit("连接失败");
			}
		}
	}
    function setdebug($debug)
    {
    	$this->debug = $debug;

    }
    function setlang($lang)
    {
    	$this->lang = $lang;
    }
	function query($sql) {
		if($GLOBALS['_CONFIG']['db']['debug']) {
			$query = $this->pdo->query($sql);
		}else {
			$query =$this->pdo->query($sql);
		}
		$this->_querycount();
		return $query;
	}

     
	function Select($v=array())
	{
		$limit = $v['num']==""?"":" LIMIT ".$v['num'];

		$v['key'] = $v['key']==""?"id":$v['key'];

		$v['where'] = $v['where']==""?1:$v['where'];//查询条件

		$v['field'] = $v['field']!=""?implode(",",$v['field']):$v['field']="*";//字段

		$v['condition'] = $v['condition']=="" ? " ORDER BY ".$v['key']." DESC" : $v['condition'];//数据排列条件
		$v['sum']=="" ? "" : $v['sum'];

		$SQL = "SELECT ".$v['field']." FROM ".$this->table." WHERE ".$v['where'].$v['condition'].$limit;
        $this->sql = $SQL;

		$res = $this->query($SQL);
		
		$Result = $this->fetch_array($res);

		return $Result;
	}

	function SelectS($sql,$arr="")
	{
		$result = $this->query($sql); 
		if($result) {
			if($arr==1) {
				$Result = $result->fetch(PDO::FETCH_ASSOC);//使用fetch()方法获取结果  
			}
			else {
				$Result = $result->fetchAll(PDO::FETCH_ASSOC);//使用fetch()方法获取结果  
			}
		}
		else {
			$Result = array();
		}
		return $Result;
	}


	function Update($v)
	{
	    $updateStr = "";
        foreach ($v['UpdateStr'] as $key => $val) {
			if(strpos($val,"(int)")===0) {
			    $val = substr($val,5);

				$updateStr.="{$key} = {$val},";
			}
			else {

				$updateStr.="{$key} = '{$val}',";
			}
        }

        $updateStr = substr($updateStr, 0, -1);

		$SQL = "UPDATE ".$this->table." SET ".$updateStr." WHERE ".$v['where']."";
        
		if($this->pdo->exec($SQL)) {
			return true;
		}
	}

	function Insert($v)
	{
		if(!is_array($v))
		{
			$this->msg($GLOBALS['lang']['mysql_InsertError']);
		}
		$insertField = "";

		$insertValue = "";

		foreach ($v as $key => $val)
		{
			$insertField .= $key.',';

			if(strpos($val,"(int)")===0) {
				$val_ = substr($val,5);
				$insertValue.="{$val_},";
			}
			else {
				$insertValue.="'{$val}',";
			}
        }
        $insertField = substr($insertField, 0, -1);

        $insertValue = substr($insertValue, 0, -1);

		$SQL = "INSERT INTO ".$this->table."(".$insertField.") VALUES (".$insertValue.")";

        return $this->pdo->exec($SQL);
	}

	function Delete($where) {
		if(!$where) {
			$this->msg($GLOBALS['lang']['mysql_DeleteError']);
		}

		$SQL = "DELETE FROM ".$this->table." ".$where;
		if($this->pdo->exec($SQL)) {
			return true;
		}
		else {
			return false;
		}
	}

	function fetch_array($pdoRes) {
		$data = $pdoRes->fetchAll(PDO::FETCH_ASSOC);
		return $data;
	}

	function num_fields($pdoRes) {
		$fields = $pdoRes->rowCount();
		return $fields;
	}

	function num_rows($query) {
        $res = $this->query($query);
		$row_num = @mysql_num_rows($res);
		return $row_num;
	}

	function insert_id() {
		$insertid = $this->pdo->lastInsertId();
		return $insertid;
	}

	function affected_rows() {
		$affected_rows = mysql_affected_rows($this->link);
		return $affected_rows;
	}


	function fetch_one_array($sql){
		$query = $this->query($sql);
		$data  = $this->fetch_array($query);
		return $data;
	}

	function close() {
		unset($_CONFIG['db']['dsn']);
		return $this->pdo = null;
	
	}




	#私有方法

	function _querycount() {
		$this->query_num++;
	}

	function _selectdb($db)
	{
		if($GLOBALS['_CONFIG']['db']['debug'])
		{
			mysql_select_db($db,$this->link) or $this->msg();
		}else
		{

			mysql_select_db($db,$this->link);
		}
	}

	function _version() {
		$this->version = mysql_get_server_info();
		return $this->version;
	}

	function _geterror() {
		return mysql_error();
	}

	function _geterrno() {
		return intval(mysql_errno());
	}

	function msg($info='') {

		echo "<html><head>\n";
		echo "<meta http-equiv=\"Content-Type\" content=\"text/html ; charset=utf-8\">\n";
		echo "<title>Sorry!We have an error during the process.</title></head>\n<body>\n";
		echo "<table width=\"65%\"  align=\"center\"  cellpadding=\"2\" cellspacing=\"2\" style=\"border:1px solid #ccc\">";
		echo "<tr><td style=\"line-height:22px;font-size:12px;font-family:tahoma;color:#666;\">\tWaring!MYSQL DataBase Query Error:<br /> ".$info." <br />";
	    echo "MYSQL error information:<br /><font color='red'><strong>".$this->_geterror()."</strong></font><br />";
	    echo "MYSQL error number:<br />".$this->_geterrno()."<br />\n";
		echo "Time: <br />".gmdate("Y-n-j g:ia", time() + (8 * 3600))."<br />\n";
		echo "File: <br />".$_SERVER['PHP_SELF']."<br /></td></tr>\n";
		echo "</table>\n</body>\n</html>\n";
		exit;
	}

}
?>